﻿using Communication.Channel;
using Communication.Message.Osc;
using growatt.Message.Osc;
using Growatt.DuiHelpers;
using Growatt.WaveData.DataSetResolve;
using Oscilloscope.Util;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Vosc;
using Vosc.VirtualOscilloscope;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Growatt.WaveData.VirtualOscilloscope
{
    public partial class UC_ParameterWriting : UserControl
    {
        public UC_ParameterWriting()
        {
            InitializeComponent();
            comboBox_scale.SelectedIndex = 0;
            comboBox_type.SelectedIndex = 0;
            MainForm.getChannelHelper += (s) =>
            {
                channel = s;
            };
            textBox_ParaName.Text = OscilloscopeControl.ModelAppSettingsCustom.WriteValueName;
            textBox1.Text = OscilloscopeControl.ModelAppSettingsCustom.WriteValue;
        }
        // Token: 0x040000AC RID: 172
        public Channel channel;
        public enum ScaleDataType
        {
            x1 = 1,
            x10 = 10,
            x100 = 100,
            x1k = 1000,
            x10k = 10000,
            x100k = 100000
        }

        public Action<string> ActionShow { get; set; }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                ActionShow?.Invoke($"");
                if (!string.IsNullOrEmpty(textBox_ParaName.Text) && !string.IsNullOrEmpty(textBox1.Text) && comboBox_scale.SelectedIndex != -1 && comboBox_type.SelectedIndex != -1)
                {
                    List<string> strings = new List<string>() { textBox_ParaName.Text };

                    VariableInfo variableInfo = new VariableInfo(textBox_ParaName.Text, string.Empty);
                    DwarfHelper.DwarfHelperInstance.GetAddress(new List<VariableInfo>() { variableInfo });
                    if (string.IsNullOrEmpty(variableInfo.Address))
                    {
                        MessageBox.Show("查询失败");
                        return;
                    }
                    var typeString = string.Empty;

                    if (!string.IsNullOrEmpty(variableInfo.SzieVar))
                    {
                        // 使用MessageBox询问是否继续
                        //DialogResult result = MessageBox.Show($"当前变量的类型:{variableInfo.SzieVar},是否继续设置?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        //if (result != DialogResult.Yes)
                        //{
                        //    return;
                        //}
                        typeString = variableInfo.SzieVar;
                        ENUM_001 ty_ENUM_001 = ENUM_001.I16;
                        if (typeString.Contains("unsigned"))
                        {
                            ty_ENUM_001 = ENUM_001.U16;
                        }
                        else if (typeString.Contains("float"))
                        {
                            ty_ENUM_001 = ENUM_001.F32;
                        }
                        else
                        {
                            ty_ENUM_001 = ENUM_001.I16;
                        }
                        comboBox_type.Text = Enum.GetName(typeof(ENUM_001), ty_ENUM_001);
                    }
                    if (!string.IsNullOrEmpty(variableInfo.Address))
                    {
                        double dataf = 1;
                        if (Enum.TryParse(comboBox_scale.Text, out ScaleDataType type) && double.TryParse(textBox1.Text, out double valToSet))
                        {
                            dataf = (double)type * dataf * valToSet;
                        };
                        var f = variableInfo.Address;
                        ActionShow?.Invoke($"地址:{f},类型:{variableInfo.SzieVar}");
                        Console.WriteLine($"地址:{f}");
                        var ad = Convert.ToInt32(f, 16);
                        var SignalRatio = (byte)(ENUM_Ratio)Enum.Parse(typeof(ENUM_Ratio), (string)comboBox_scale.SelectedItem); //数据倍率
                        var SignalType = (byte)(ENUM_001)Enum.Parse(typeof(ENUM_001), (string)comboBox_type.SelectedItem); //数据类型
                        var ty = (ENUM_001)Enum.Parse(typeof(ENUM_001), (string)comboBox_type.SelectedItem);
                        byte reType = 0;
                        if (typeString.Contains("unsigned"))
                        {
                            ty = ENUM_001.U16;
                        }
                        else if (typeString.Contains("float") )
                        {
                            ty = ENUM_001.F32;
                        }
                        else
                        {
                            ty = ENUM_001.I16;
                        }
                        switch (ty)
                        {
                            case ENUM_001.U16:
                                reType = 0;
                                break;

                            case ENUM_001.I16:
                                reType = 1;
                                break;
                            case ENUM_001.F32:
                                reType = 2;
                                break;
                            default:
                                break;
                        }
                        ConfigDataChanelMessage addrSetChannelMessage = new ConfigDataChanelMessage(new int[] { ad }, reType, SignalRatio, (int)dataf);//发送所有地址信息(地址设置)
                        addrSetChannelMessage.SetSendTimeoutMillis(1000);
                        addrSetChannelMessage.SetSpaceReceiveTimeoutMillis(1000);
                        addrSetChannelMessage.SetTotalReceiveTimeoutMillis(1000);

                        try
                        {
                            var val = MainForm.ChannelWriters?.Invoke(addrSetChannelMessage);
                            if (!val.Value)
                            {
                                channel?.Close();
                                return;
                            }
                            Thread.Sleep(300);
                            //if (!addrSetChannelMessage.IsSuccess())
                            //{
                            //    ActionShow?.Invoke($"参数设置消息处理失败");
                            //    channel?.Close();
                            //    MessageBox.Show($"参数设置消息处理失败");
                            //    throw new Exception("参数设置消息处理失败", addrSetChannelMessage.GetCause());
                            //}
                            //if (addrSetChannelMessage.ErrorCode != OscErrorCode.SUCCESS)
                            //{
                            //    channel?.Close();
                            //    ActionShow?.Invoke($"参数设置消息处理失败");
                            //    MessageBox.Show($"参数设置消息处理失败");
                            //    throw new Exception("参数设置消息处理失败", new Exception("消息错误码不是 SUCCESS"));
                            //}
                            ActionShow?.Invoke($"地址:{f},类型:{variableInfo.SzieVar}");
                            MessageBox.Show($"下发设置参数成功,地址:{f}");
                            channel?.Close();
                        }
                        catch (Exception ex)
                        {
                            DuiHelperLog.WriteErrorLog(ex);
                        }
                    }
                    else
                    {
                        ActionShow?.Invoke($"请检查是否存在当前变量");
                        Console.WriteLine("请检查是否存在当前变量!");
                    }
                }
                else
                {
                    ActionShow?.Invoke($"请检查输入值!");
                    Console.WriteLine("请检查输入值");
                }
            }
            catch (Exception ex)
            {
                DuiHelperLog.WriteErrorLog(ex);
            }
            finally
            {
                channel?.Close();
            }
        }

        private void textBox_ParaName_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox_ParaName.Text))
                OscilloscopeControl.ModelAppSettingsCustom.WriteValueName = textBox_ParaName.Text;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text))
                OscilloscopeControl.ModelAppSettingsCustom.WriteValue = textBox1.Text;
        }
    }
}
